package ec;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Generation {
	private int _generation = 0;
	private double[] _fitness_values = null;
	private String[] _strings = null;
	private String[] _solution_strings = null;
	private List<HashMap<String, Object>> _info = null;
	private long _elapsed_time = 0;
	private int _best_index;

	protected Generation(int generation, List<Solution> solutions) {
		_generation = generation;
		_fitness_values = new double[solutions.size()];
		_strings = new String[solutions.size()];
		_solution_strings = new String[solutions.size()];
		_info = new ArrayList<HashMap<String, Object>>(solutions.size());

		// Store the fitness values, a string representation, and the solution
		// string (phenotypic string representation)
		double best = Double.NEGATIVE_INFINITY;
		for (int i = 0; i < _fitness_values.length; i++) {
			_fitness_values[i] = solutions.get(i).getFitness();
			if (_fitness_values[i] > best) {
				best = _fitness_values[i];
				_best_index = i;
			}

			_info.add((HashMap<String, Object>) solutions.get(i).getInfo()
					.clone());
			_strings[i] = solutions.get(i).toString();
			_solution_strings[i] = solutions.get(i).getSolutionString();
		}
	}

	public int getBestIndex() {
		return _best_index;
	}

	void setElapsedTime(long elapsed_time) {
		_elapsed_time = elapsed_time;
	}

	public int getGeneration() {
		return _generation;
	}

	public double[] getFitnessValues() {
		return _fitness_values;
	}

	public double getFitnessValue(int index) {
		return _fitness_values[index];
	}

	public String getString(int index) {
		return _strings[index];
	}

	public String getSolutionString(int index) {
		return _solution_strings[index];
	}

	public long getElapsedTime() {
		return _elapsed_time;
	}

	public String toString() {
		StringBuilder str = new StringBuilder();
		str.append(getGeneration());
		str.append(": time=");
		str.append(getElapsedTime());
		str.append("\n");
		for (double f : getFitnessValues()) {
			str.append(f);
			str.append(" ");
		}
		str.append('\n');
		// str.append(getSolutionString(_best_index));
		// str.append('\n');
		str.append(getString(_best_index));
		str.append('\n');

		return str.toString();
	}

	public HashMap<String, Object> getInfo(int index) {
		return _info.get(index);
	}
}
